<template>
  <view class="container">
    <!-- 用户信息表单 -->
    <view class="form-container">
      <!-- 头像上传 -->
      <view class="form-item avatar-item">
        <view class="item-label">头像</view>
        <view class="avatar-upload" @click="chooseAvatar">
          <image v-if="userInfo.headPicture" :src="avatarUrl" class="avatar-image" mode="aspectFill"></image>
          <view v-else class="avatar-placeholder">
            <uni-icons type="camera" size="24" color="#999"></uni-icons>
          </view>
        </view>
      </view>

      <!-- 昵称 -->
      <view class="form-item">
        <view class="item-label">昵称</view>
        <input v-model="userInfo.nikeName" class="item-input" placeholder="请输入昵称" maxlength="20" />
      </view>

      <!-- 真实姓名 -->
      <view class="form-item">
        <view class="item-label">真实姓名</view>
        <input v-model="userInfo.name" class="item-input" placeholder="请输入真实姓名" maxlength="10" />
      </view>

      <!-- 手机号 -->
      <view class="form-item">
        <view class="item-label">手机号</view>
        <input v-model="userInfo.phone" class="item-input" placeholder="请输入手机号" type="number" maxlength="11" />
      </view>
      <view class="bottom-container">
        <!-- 头部导航 -->
        <view class="bottom-btn" @click="saveUserInfo">
          <text class="save-btn">保存</text>
        </view>
        <!-- 提示信息 -->
        <view class="tips">
          <text class="tips-text">* 以上信息均为选填，可根据需要完善</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { API,config } from '@/utils/api.js'
export default {
  name: "myInfo",
  data() {
    return {
      userInfo: {
        userId: null,
        nikeName: '',
        phone: '',
        headPicture: '',
        name: ''
      },
      isSaving: false
    }
  },
  computed: {
   avatarUrl() {
      if (!this.userInfo.headPicture) return ''
      // 如果是http或https开头，直接返回
      if (/^https?:\/\//.test(this.userInfo.headPicture)) {
        return this.userInfo.headPicture
      }
      // 否则拼接服务器地址
      // 兼容 / 开头和无 / 开头
      if (this.userInfo.headPicture.startsWith('/')) {
        return config.baseURL + this.userInfo.headPicture
      } else {
        return config.baseURL + '/' + this.userInfo.headPicture
      }
    }   
  },
  onLoad() {
    this.getUserInfo()
  },
  methods: {
    // 返回上一页
    goBack() {
      uni.navigateBack()
    },

    // 获取用户信息
    async getUserInfo() {
      try {
        uni.showLoading({ title: '加载中...' })
        const result = await API.user.getUserInfo()
        if (result) {
          this.userInfo = {
            userId: result.userId || null,
            nikeName: result.nikeName || '',
            phone: result.phone || '',
            headPicture: result.headPicture || '',
            name: result.name || ''
          }
        }
      } catch (error) {
        console.error('获取用户信息失败:', error)
        uni.showToast({
          title: '获取用户信息失败',
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
      }
    },

    // 选择头像
    chooseAvatar() {
      uni.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          console.log(res)
          this.uploadAvatar(res.tempFilePaths[0])
        }
      })
    },

    // 上传头像
    async uploadAvatar(filePath) {
      try {
        uni.showLoading({ title: '上传中...' })
        const result = await API.user.uploadAvatar(filePath)
        console.log(result)
        if (result && result.fileName) {
          this.userInfo.headPicture = result.fileName
          uni.showToast({
            title: '头像上传成功',
            icon: 'success'
          })
        }
      } catch (error) {
        console.error('头像上传失败:', error)
        uni.showToast({
          title: '头像上传失败',
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
      }
    },

    // 保存用户信息
    async saveUserInfo() {
      if (this.isSaving) return

      // 验证手机号格式
      if (this.userInfo.phone && !/^1[3-9]\d{9}$/.test(this.userInfo.phone)) {
        uni.showToast({
          title: '请输入正确的手机号',
          icon: 'none'
        })
        return
      }

      try {
        this.isSaving = true
        uni.showLoading({ title: '保存中...' })

        const result = await API.user.updateUserInfo(this.userInfo)
        if (result && result.code === 200) {
          uni.showToast({
            title: '保存成功',
            icon: 'success'
          })

          // 更新本地存储的用户信息
          const localUserInfo = uni.getStorageSync('userInfo')
          if (localUserInfo) {
            const parsedInfo = JSON.parse(localUserInfo)
            const updatedInfo = { ...parsedInfo, ...this.userInfo }
            uni.setStorageSync('userInfo', JSON.stringify(updatedInfo))
          }

          // 延迟返回上一页
          setTimeout(() => {
            uni.navigateBack()
          }, 1500)
        } else {
          uni.showToast({
            title: result.message || '保存失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('保存用户信息失败:', error)
        uni.showToast({
          title: '保存失败',
          icon: 'none'
        })
      } finally {
        this.isSaving = false
        uni.hideLoading()
      }
    }
  }
}
</script>

<style scoped>
.container {
  background: #ffffff;
  min-height: 100vh;
}

.save-btn {
  color: #fff;
  font-size: 28rpx;
  font-weight: 500;
}

/* 表单容器 */
.form-container {
  background: #ffffff;
  margin-top: 24rpx;
  border-radius: 16rpx;
  margin: 24rpx 16rpx 0 16rpx;
  overflow: hidden;
}

.form-item {
  display: flex;
  align-items: center;
  padding: 32rpx 24rpx;
  border-bottom: 1rpx solid #f5f5f5;
}

.form-item:last-child {
  border-bottom: none;
}

.avatar-item {
  padding: 40rpx 24rpx;
}

.item-label {
  width: 160rpx;
  font-size: 30rpx;
  color: #333;
  font-weight: 500;
}

.item-input {
  flex: 1;
  font-size: 30rpx;
  color: #333;
  padding: 0;
  margin-left: 24rpx;
}

.item-input::placeholder {
  color: #999;
}

/* 头像上传 */
.avatar-upload {
  width: 120rpx;
  height: 120rpx;
  border-radius: 60rpx;
  overflow: hidden;
  background: #ffffff;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-left: 24rpx;
  border: 1rpx solid #e8e8e8;
}

.avatar-image {
  width: 100%;
  height: 100%;
}

.avatar-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #ffffff;
  border: 1rpx solid #e8e8e8;
}

/* 提示信息 */
.tips {
  padding: 32rpx 16rpx;
}

.tips-text {
  font-size: 26rpx;
  color: #999;
  line-height: 1.5;
}

.bottom-btn {
  background: #C6282B;
  border-radius: 44rpx;
  height: 88rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 32rpx;
}

.bottom-container {
  margin: 40rpx 16rpx;
  background: #ffffff;
  padding: 20rpx;
}
</style>